import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex)
import {
	login,
	getUserInfo
} from '../api/index.js'

import store from '@/store'

import router from '../router/index.js'
import {
	getRouters
} from "../utils"
var token = localStorage.getItem('token') || false
export default new Vuex.Store({
	state: {
		token,
		router:[],
		activeName:"user",
		activeshowName:"权限",
		activesubName:"userlist",
		userInfo: ""
	},
	getters: {
		isAuthenticated: state => {
			return state.token
		}
	},
	mutations: {
		setRouter(){}
	},
	actions: {
		setmenu({  state }, active){
			if(active.length>0){
				state.activeName =active[0].name
				state.activeshowName =active[0].meta.title
				state.activesubName =active[1].name
			}
			
		},
		login({  state }, userData) {
			return new Promise((resolve, reject) => {
				let name = userData.user.trim()
				let password = userData.password
				let data = {
					name,
					password
				}
				const res = login(data);
				res.then(result => {
						var {
							data: {
								token
							}
						} = result;
						state.token = token;
						localStorage.setItem('token', token)
						resolve(true)
					})
					.catch(err => {
						reject(err)
					})
			})
		
		},
		setRouter({ state }){
			var routers = getRouters()
				routers.then(res=>{
					router.addRoutes(res)
					state.router = res;
				})
		},
		getUserInfo({ state ,dispatch}) {
			return new Promise((resolve, reject) => {
				const res = getUserInfo()
				res.then(res => {
					let {
						userInfo
					} = res.data;
					state.userInfo = userInfo;
					store.dispatch
					dispatch('setRouter')
					resolve(true)
				}).catch(err => {
					reject(err)
				})
			})
		}
	},
	modules: {}
})


